package com.lxitedu.dao.impl.ibatis;

import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.SneakyThrows;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.lxitedu.bean.EmailData;
import com.lxitedu.dao.EmailDataDao;
import com.lxitedu.utils.LxitException;

public class EmailDataDaoImpl implements EmailDataDao {

  private SqlMapClient        sqlMapClient;
  private static final String SQL_MAP_CONFIG_PATH = "com/lxitedu/dao/impl/ibatis/sqlMapConfig.xml";
  private String              tableName;

  public EmailDataDaoImpl() {
    try {
      Reader reader = Resources.getResourceAsReader(SQL_MAP_CONFIG_PATH);
      sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
      reader.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void createTable(String tableName) throws LxitException {
    try {
      sqlMapClient.update("createTable", tableName);
    } catch (Exception e) {
      e.printStackTrace();
      throw new LxitException("Table is already exist!");
    }
    this.tableName = tableName;
  }

  private void check() throws LxitException {
    if (tableName == null) {
      throw new LxitException("Please create a database first!");
    }
  }

  @Override
  @SneakyThrows
  public EmailData add(EmailData emailData) throws LxitException {
    check();
    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("tableName", tableName);
    paramMap.put("emailData", emailData);
    sqlMapClient.insert("insertEmailData", paramMap);
    return emailData;
  }

  @Override
  @SneakyThrows
  public List<?> getAll() {
    return sqlMapClient.queryForList("selectAllEmailData", tableName);
  }

  @Override
  @SneakyThrows
  public EmailData getByUrl(String url) {
    Map<String, String> paramMap = new HashMap<String, String>();
    paramMap.put("tableName", tableName);
    paramMap.put("url", url);
    return (EmailData) sqlMapClient.queryForObject("selectEmailDataByUrl",
        paramMap);
  }
}
